﻿//========================================================================//
//      Copyright 2012, Smilodon Studio Inc.
//      All rights reserved.
//========================================================================//

/**
 *	game
 *      @author: CYS
 */


var canvas;
var gl;
var infoPad;

var timer = {time: 0, dtime: 0, startime: Date.now(), lasttime: Date.now() };
var mouse = {x: 0, y: 0, x0: 0, y0: 0, dx: 0, dy: 0, down: false};

var cameraFPS;
var carBody = [];
var flowers = [];
var terrain;
var skyBox;
var iceGround;
var modelScale = 1.0;

var polys = [];
var kw = false;
var ks = false;
var ka = false;
var kd = false;
var maxSpeed = 5;

// ----------------------------------------------------------------------------
// initlalize

function canvasResize()
{
	canvas.width = window.innerWidth;
	canvas.height = window.innerHeight;

	attribs = { antialias:true };
	if(!gl) gl = initWebGL(canvas,attribs);
	gl.viewportWidth = canvas.width;
	gl.viewportHeight = canvas.height;

	if(!cameraFPS)cameraFPS = new camera();
	cameraFPS.setProj(50, gl.viewportWidth, gl.viewportHeight, 1, 15000);
	cameraFPS.pos.e[1] = 50;
	cameraFPS.pos.e[2] = 1000;


}

function init()
{
	canvas = document.getElementById('webgl-canvas');
	canvasResize();

	var touchable = 'createTouch' in document;
	if (touchable)
	{
		canvas.addEventListener('touchstart', onTouchStart, false);
		canvas.addEventListener('touchmove', onTouchMove, false);
		canvas.addEventListener('touchend', onTouchEnd, false);
	}
	else
	{
		canvas.addEventListener('mousedown', onTouchStart, false);
		canvas.addEventListener('mousemove', onTouchMove, false);
		canvas.addEventListener('mouseup', onTouchEnd, false);
		window.addEventListener('keydown', onKeyDown, false);
		window.addEventListener('keyup', onKeyUp, false);
	}

	canvas.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );

	infoPad = new infoShow();
	infoPad.add("Speed game", "@Smilodon Studio");
	infoPad.add("mouse.dx", mouse.dx);
	infoPad.add("mouse.dy", mouse.dy);


	var cubeFiles =
		[
			"./res/posx.jpg",
			"./res/negx.jpg",
			"./res/posy.jpg",
			"./res/negy.jpg",
			"./res/posz.jpg",
			"./res/negz.jpg"
		];

	skyBox = new sky(cubeFiles);
	iceGround = new water(cubeFiles);

	var carBodyFiles =
			[
				"./res/test.ctm"
				//,"./res/test.ctm"
				//,"./res/car1.ctm"
				//,"./res/car_black.ctm"
			];
	for(var i = 0; i < carBodyFiles.length; i++)
	{
		var c = new model(carBodyFiles[i], "./res/test.jpg");
		carBody.push(c);

	}
	//var flower = new model("./res/flower.json", "./res/flower.jpg");

	//for(var i = -2; i < 2; i++)
	//for(var j = -2; j < 2; j++)
	//{
	//	var f = {};
	//	f.model = flower;
	//	f.pos = new vec3(i*400, 0, j*400);
	//	f.visble = true;
	//	flowers.push(f);
	//}



}


// ----------------------------------------------------------------------------
// scene

function drawScene()
{
	gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);

	gl.clearColor(0.0, 0.72, 0.89, 1.0);
	gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
	update();

	for(var i = 0; i < flowers.length; i++)
	{
		var d = (car.pos.sub(flowers[i].pos)).length;
		var r = car.r + flowers[i].r;
		if(d < r) flowers[i].visble = false;
	}

	// camera
	if(mouse.down)
	{
		if(mouse.dx > 200 ) mouse.dx = 200;
		if(mouse.dx < -200 ) mouse.dx = -200;

		cameraFPS.vYaw = mouse.dx*0.0001;
		cameraFPS.vPitch = -mouse.dy*0.0001;
	}

	cameraFPS.vYaw *= 0.89;
	cameraFPS.yaw += cameraFPS.vYaw;

	cameraFPS.vPitch *= 0.78;
	cameraFPS.pitch += cameraFPS.vPitch;
	if(cameraFPS.pitch > Math.PI*0.063 ) cameraFPS.pitch = Math.PI*0.063;
	if(cameraFPS.pitch < -Math.PI*0.063 ) cameraFPS.pitch = -Math.PI*0.063;

	cameraFPS.vx *= 0.98;
	cameraFPS.vz *= 0.98;
	cameraFPS.pos.e[0] += cameraFPS.vx;
	cameraFPS.pos.e[2] += cameraFPS.vz;
	cameraFPS.setView2(cameraFPS.pos, cameraFPS.pitch*0.9, cameraFPS.yaw);
	//cameraFPS.setView2(cameraFPS.pos, 0, 0);
	//cameraFPS.setView(cameraFPS.pos, new vec3(0,0,1));


	// skyBox
	gl.disable(gl.DEPTH_TEST);
	var matIVP = matMul(cameraFPS.matProj, cameraFPS.matSkyView);
	skyBox.draw(matIVP.inverse());

	// scene
	gl.enable(gl.DEPTH_TEST);

	// car


	var axisX = new vec3(1, 0, 0);
	var axisY = new vec3(0, 1, 0);
	//var axisZ = new vec3(0, 0, 1);
	var matT = mat4.makeTranslate(carBody[0].center.x, -220, carBody[0].center.z);
	var matR0 = mat4.makeRotate(-Math.PI*0.50, axisX);
	var matR1 = mat4.makeRotate(Math.PI, axisY);
	var matSS = mat4.makeScale(modelScale, modelScale, modelScale);
	var matMVP = matMul(cameraFPS.matVP, matT.x(matR1.x(matR0.x(matSS))) );

	for(var i = 0; i < carBody.length; i++)
	{
		var car = carBody[i];
		if(car.isLoaded())
		{
			car.set();
			car.setMVP(matMVP);
			car.draw();

			//var matMirror = new mat4([1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
			//var matMVPM = matMul(cameraFPS.matVP, matMirror.x(matT) );
			//car.setMVP(matMVPM);
			//car.draw();
		}
	}


	for(var i = 0; i < flowers.length; i++)
	{
		var m = flowers[i].model;
		m.set();
		var e = flowers[i].pos.e;
		var matT = mat4.makeTranslate( e[0], e[1], e[2]);
		var matS = mat4.makeScale( 2, 2, 2);
		var matMVP = matMul(cameraFPS.matVP, matT.x(matS));

		if( flowers[i].visble)
		{
			m.setMVP(matMVP);
			m.draw();

			//var matMVPMi = matMul(matMVP, matMirror );
			//m.setMVP(matMVPMi);
			//m.draw();
		}

	}


	gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
	gl.enable(gl.BLEND);

	iceGround.draw(cameraFPS.matVP);

	infoPad.show();

}

// ----------------------------------------------------------------------------
// Input Proccess

function onKeyUp(event)
{
	// `~
	if(event.keyCode == 192)infoPad.visble = ! infoPad.visble;

	var b = event.keyCode;
	if(b==38 || b==87) kw = false;
	else if(b==40 || b==83)ks = false;
	else if(b==37 || b==65)ka = false;
	else if(b==39 || b==68)kd = false;
	//infoPad.add("键盘码", event.keyCode);

};

function onKeyDown(event)
{
	var b = event.keyCode;
	if(b==38 || b==87) kw = true;
	else if(b==40 || b==83)ks = true;
	else if(b==37 || b==65)ka = true;
	else if(b==39 || b==68)kd = true;

};


function update()
{
	var w = kw ? 1 : 0;
	var s = ks ? -1 : 0;
	var ws = (w + s)*0.5;

	if(ws > 0.1)ws -= Math.sqrt(cameraFPS.vx*cameraFPS.vx + cameraFPS.vz*cameraFPS.vz) * 0.075;
	if(ws < -0.1)ws += Math.sqrt(cameraFPS.vx*cameraFPS.vx + cameraFPS.vz*cameraFPS.vz) * 0.075;
	cameraFPS.vx += ws*cameraFPS.dir.e[0];
	cameraFPS.vz += ws*cameraFPS.dir.e[2];

	var a = ka ? 1 : 0;
	var d = kd ? -1 : 0;
	var ad = -(a + d)*0.5;

	if(ad > 0.1)ad -= Math.sqrt(cameraFPS.vx*cameraFPS.vx + cameraFPS.vz*cameraFPS.vz) * 0.075;
	if(ad < -0.1)ad += Math.sqrt(cameraFPS.vx*cameraFPS.vx + cameraFPS.vz*cameraFPS.vz) * 0.075;
	cameraFPS.vx += -ad*cameraFPS.dir.e[2];
	cameraFPS.vz += ad*cameraFPS.dir.e[0];

}


function onTouchStart(event)
{
	// Prevent the browser from doing its default thing (scroll, zoom)
	event.preventDefault();


	if(event.clientX) // on mouse down
	{
		mouse.x = mouse.x0 = event.clientX;
		mouse.y = mouse.y0 = event.clientY;
		infoPad.add("mouse.x", mouse.x0);
		infoPad.add("mouse.y", mouse.y0);

		mouse.down = true;
	}

	if(!event.touches) return;
	// on touch star
	for(var i = 0; i < event.touches.length; i++)
	{
		var mx = event.touches[i].clientX;
		var my = event.touches[i].clientY;

	}

}

function onTouchMove(event)
{
	event.preventDefault();

	if(event.clientX && mouse.down) // on mouse move
	{
		mouse.dx = event.clientX - mouse.x0;
		mouse.dy = event.clientY - mouse.y0;
		mouse.x = event.clientX;
		mouse.y = event.clientY;

		infoPad.add("mouse.dx", mouse.dx);
		infoPad.add("mouse.dy", mouse.dy);

	}

	if(!event.touches) return;

	for(var i = 0; i < event.touches.length; i++)
	{

	}
}

function onTouchEnd(event)
{
	event.preventDefault();

	if(event.clientX) // on mouse up
	{
		mouse.down = false;
		mouse.dx = 0;
		mouse.dy = 0;
	}
	if(!event.touches) return;

	for(var i = 0; i < event.touches.length; i++)
	{

	}

}



var bTimeout = false;
window.onresize = function()
{
	canvasResize();
	bTimeout = true;
	//cameraFPS.setProj(70, gl.viewportWidth, gl.viewportHeight, 0.1, 5000);

}

var first = true;
var lastOrien;
window.ondeviceorientation =  function(e)
{
	if(first)
	{
		lastOrien = window.orientation;
		first = false;
	}
	if(window.orientation !== lastOrien)
	{
		window.onresize();
		lastOrien = window.orientation;
	}

	//infoPad.add("alpa: ", e.alpha);
	//infoPad.add("beta: ",e.beta);
	//infoPad.add("gamma: ",e.gamma);
	//infoPad.add("orientation: ",window.orientation);
}

window.onblur = function()
{
	bTimeout = true;
}

// ----------------------------------------------------------------------------
// game

function gameloop()
{
	window.requestAnimFrame( gameloop );
	if(bTimeout)
	{
		timer.lasttime = Date.now();
		bTimeout = false;
	}
	timer.dtime = Date.now() - timer.lasttime;
	timer.time = Date.now() - timer.startime;
	drawScene();
	timer.lasttime = Date.now();
}


function game()
{
	init();
	gameloop();
}

// ----------------------------------------------------------------------------



